package com.crhms.seabow.controller;

import com.crhms.seabow.entity.Word;
import com.crhms.seabow.repository.WordRepository;
import com.crhms.seabow.service.SubtitleService;
import com.crhms.seabow.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/import")
public class ImportController {

    @Autowired
    private SubtitleService subtitleService;

    @Autowired
    private WordService wordService;

    @RequestMapping("/run")
    public String run(){
        //String path = "C:\\Users\\hkk\\Desktop\\日本語\\初级下册\\课文原文";
        String path = "C:\\Users\\hkk\\Desktop\\日本語\\初级上册\\课文txt";

        File folder = new File(path);
        File[] files = folder.listFiles();

        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            List<String> txts = readTxt(file,"UTF-8");
            String name = file.getName().replace(".txt","");
            subtitleService.saveSubtitles(Integer.parseInt(name),txts);
        }

        return "ok";
    }

    @RequestMapping("/word")
    public String word(Integer id){
        String path = "C:\\Users\\hkk\\Desktop\\日本語\\初级上册\\单词txt";

        File folder = new File(path);
        File[] files = folder.listFiles();
        List<Word> words = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (file.isFile() && !file.getName().contains("xlsx")) {
                String lesson = file.getName().replace("Lesson","").replace(".txt","");
                int lessonId = Integer.parseInt(lesson);
                //如果没传Id，则导出全部
                //如果传入的Id = LessonId则导入指定Id
                if (StringUtils.isEmpty(id) || lessonId ==id ){
                    List<String> txts = readTxt(file,"UTF-8");
                    txts.forEach(t->{
                        Word word = getWord(t);
                        if (Objects.nonNull(word)){
                            word.setLessonId(lessonId);
                            //wordRepository.insert(word);

                            words.add(word);
                        }
                    });
                }

            }
            System.out.println(String.format("第%d个文件，上传完成", i));
        }

        if (!CollectionUtils.isEmpty(words)) {
            wordService.batchInsert(words);
        }
        return "ok";
    }

    private Word getWord(String txt){
        Word word = new Word();
        String chinese =null;
        String cagetory = null;
        String kana = null;
        String comment =null;
        if (StringUtils.isEmpty(txt)) {
            return null;
        }

        txt = txt.replace("（","(").replace("）",")");
        txt = txt.replace("［","[").replace("］","]");

        //中文假名
        if (txt.contains("(")) {
            chinese = txt.substring(txt.indexOf('('),txt.indexOf(')')+1);
            word.setChinese(chinese.replace("(","").replace(")",""));
        }
        //词性
        if (txt.contains("[")) {
            cagetory = txt.substring(txt.indexOf('['),txt.indexOf(']')+1);
            word.setCategory(cagetory.replace("[","").replace("]",""));
        }
        //译文
        if (txt.contains("]")) {
            comment = txt.substring(txt.indexOf(']')+1);
            word.setComment(comment);
        }else if (txt.contains(")")){
            comment = txt.substring(txt.indexOf(')')+1);
            word.setComment(comment);
        }

        //假名
        if (txt.contains("(")) {
            kana = txt.substring(0,txt.indexOf('('));
            word.setKana(kana.trim().replace("　　",""));
        }else if (txt.contains("[")){
            kana = txt.substring(0,txt.indexOf('['));
            word.setKana(kana.trim().replace("　　",""));
        } else {
            word.setKana(txt);
        }

        word.setCreateDate(LocalDateTime.now());
        return word;
    }

    public static List<String> readTxt(File file,String charsetName) {
        BufferedReader reader = null;
        try{
//            String fileEncode= EncodingDetect.(file);
//            String fileContent= FileUtils.readFileToString(new File(file),fileEncode);

            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream((file)),charsetName);
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            int line = 1;
            List<String> text = new ArrayList<>();
            while ((tempString = reader.readLine()) != null) {
                text.add(tempString);
                line++;
            }
            reader.close();
            return text;

        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (reader != null){
                try{
                    reader.close();
                }catch (IOException e1){

                }
            }
        }
        return null;
    }
}
